const log4js = require('koa-log4');
const logger = log4js.getLogger('routes::staff');
const router = require('koa-router')();
exports = module.exports = router;
const mongodb = require('mongodb');
const ObjectId = mongodb.ObjectId;

const _ = require('lodash');
const util = require(global.prefixPath + '/commons/util');
const site_service = require(global.prefixPath + '/services/site');
const info_service = require(global.prefixPath + '/services/info');
const categories = require(global.prefixPath + '/data/industries.json');
router.get('/', async (ctx, next) => {
    try {
        let site = ctx.site;
        return ctx.redirect('/' + site.subDomain + '/');
    } catch (err) {
        throw err;
    }
});
router.get('/:city/', async (ctx, next) => {

    try {

        let site_id = ctx.site._id;
        let fields = {adsenses: 1, _id: 0};
        let adsenses = (await site_service.findById(site_id, fields)).adsenses;
        let allids = [];
        for (let key in adsenses) {
            allids = allids.concat(adsenses[key]);
        }
        allids = util.toObjectId(allids);

        let allads = await info_service.findByIds(allids);

        // 组合数据
        for (let key in adsenses) {
            let ads = _.filter(allads, (val) => {
                return _.indexOf(adsenses[key], val._id.toString()) >= 0;
            });
            adsenses[key] = ads;
        }

        // 获取最新成交信息
        let traded = {
            query: {
                isTraded: true,
                site: site_id
            },
            sort: {
                tradedAt: -1
            },
            page: {
                index: 1,
                size: 16
            }
        }
        let tradedResult = await info_service.find(traded)

        // 获取个人发布的求租信息
        let seeklease = {
            query: {
                infoType: 'SeekLease',
                infoSource: 'PERSONAL',
                site: site_id
            },
            sort: {
                created: -1
            },
            page: {
                index: 1,
                size: 12
            }
        }
        let seekResult = await info_service.find(seeklease);
        ctx.state.traded = tradedResult;
        ctx.state.seek = seekResult;
        ctx.state.adsenses = adsenses;
        ctx.state.categories = categories;
    } catch (err) {
        throw err;
    }

    return await ctx.render('home/index');
});
